package com.ray.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class DbUtil
{
    // 指定数据库连接配置文件名称
    private static final String configFile = "db.properties";
    private static final Logger logger = LogManager.getLogger(DbUtil.class);
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    // 静态代码块,在类加载的时候执行
    static
    {
        init();
    }

    /**
     * 初始化函数，使用本类中的其他方法时会执行本函数
     */
    public static void init()
    {

        // 新建properties操作类
        Properties params = new Properties();

        // 读取configfile
        InputStream is = DbUtil.class.getClassLoader().getResourceAsStream(configFile);
        try
        {
            params.load(is);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        // 载入四个连接参数，驱动， url， 用户名和密码
        driver = params.getProperty("driver");
        url = params.getProperty("url");
        user = params.getProperty("user");
        password = params.getProperty("password");
    }

    /**
     * 创建数据库连接
     *
     * @return Connection
     */
    public static Connection getConnetion()
    {
        // 声明一个Connection对象
        Connection connection = null;

        try
        {
            // 注册驱动
            Class.forName(driver);

            // 获取数据库连接对象
            connection = DriverManager.getConnection(url, user, password);
            logger.info("创建连接完成");
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return connection;
    }

    /**
     * 查询操作
     *
     * @param connection 数据库连接，用来进行事物处理
     * @param sql        带参数的sql语句
     * @param params     参数
     * @return
     * @throws Exception
     */
    public static ResultSet query(Connection connection, String sql, Object[] params) throws Exception
    {
        // 创建两个对象
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        // 直接调用执行函数
        return execute(connection, preparedStatement, resultSet, sql, params);
    }

    /**
     * 查询操作
     *
     * @param connection 数据库连接，用来进行事物处理
     * @param pstm       PreparedStatement
     * @param rs         返回的结果集
     * @param sql        sql语句
     * @param params     传入sql语句的参数
     * @return
     */
    private static ResultSet execute(Connection connection, PreparedStatement pstm, ResultSet rs, String sql, Object[] params) throws Exception
    {
        pstm = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++)
        {
            pstm.setObject(i + 1, params[i]);
        }
        logger.info(sql);
        logger.info(pstm);
        rs = pstm.executeQuery();
        logger.info(rs.getMetaData().getColumnCount());
        return rs;
    }

    /**
     * 更新操作
     *
     * @param connection
     * @param sql
     * @param params
     * @return
     * @throws Exception
     */
    public static int execute(Connection connection, String sql, Object[] params) throws Exception
    {
        int updateRows = 0;
        PreparedStatement pstm = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++)
        {
            pstm.setObject(i + 1, params[i]);
        }
        logger.info(sql);
        logger.info(pstm);
        updateRows = pstm.executeUpdate();
        return updateRows;
    }
}
